/** 
 * @Title: CountSentence.java 
 * @Package wordrelationship.dao 
 * @Description: TODO
 * @author HeYan
 * @date 2016年12月30日 下午5:36:02 
 */
package wordrelationship.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.zizo.util.ConnectionPool;

/**
 * @ClassName: CountSentence
 * @Description: TODO
 * @author HeYan
 * @date 2016年12月30日 下午5:36:02
 * 
 */
public class CountSentence implements Runnable {
	private Connection conn;
	private int bbscid;

	public CountSentence(Connection conn, int bbscid) {
		super();
		this.conn = conn;
		this.bbscid = bbscid;
	}

	public void getSentence() {
		Statement st = null;
		ResultSet rs = null;
		String sql = "SELECT bbs_content from autohome_syn.bbs_c_" + bbscid;
		int natureID = 0;// 自然段ID
		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				String content = rs.getString(1);
				String[] conArr = content.split("\n");
				for (String s : conArr) {
					int senID = 0;// 句子index
					int natureLen = s.length();// 每段长度
					String[] senArr = s.split("\\}\\{|\\?");
					int senCount = senArr.length;// 每段句子个数
					for (String sen : senArr) {
						int senLen = sen.length();// 句子长度
						senID++;
						insert(natureID, natureLen, senCount, senID, senLen);
					}
				}
				natureID++;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void insert(int natureID, int natureLen, int senCount, int senID, int senLen) {
		Statement st = null;
		String sql = "INSERT INTO ProjectTemp.nature_" + bbscid + "(natureID,natureLen,senCount,senID,senLen) values("
				+ natureID + "," + natureLen + "," + senCount + "," + senID + "," + senLen + ")";
		try {
			st = conn.createStatement();	
			st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void createTable() {
		Statement st = null;
		String sql = "Create Table nature_" + bbscid + " like nature";
		try {
			st = conn.createStatement();
			st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		createTable();
		getSentence();
		System.out.println(bbscid);
	}

	public static void main(String[] args) {
		Connection conn = ConnectionPool.getConnection("ProjectTemp", "localhost");
		ExecutorService fix = Executors.newFixedThreadPool(20);
		int[] ids = { 364, 4080, 2123, 3204, 2980 };
		for (int i : ids) {
			fix.execute(new CountSentence(conn, i));
		}
		fix.shutdown();
	}
}
